import 'package:flutter/material.dart';
import 'package:shenling_logistics/components/EmptyComp.dart';
import 'package:shenling_logistics/components/TaskItem.dart';
import 'package:shenling_logistics/utils/Auth.dart';
import 'package:shenling_logistics/utils/EventBus.dart';
import 'package:shenling_logistics/utils/Http.dart';
import 'package:shenling_logistics/utils/Toast.dart';
// import 'package:shenling_logistics/utils/Auth.dart';

class WaitView extends StatefulWidget {
  const WaitView({super.key});

  @override
  State<WaitView> createState() => _WaitViewState();
}

class _WaitViewState extends State<WaitView> {
  // 任务列表
  List taskList = [];
  // 页码
  int page = 1;
  // 总页数
  int pages = 0;
  // 任务总数
  int totalCouont = 0;
  // 页尺寸
  int pageSize = 10;

  //  滚动控制器
  final ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);

    eventBus.on<UserDataInEvent>().listen((event) {
      getTaskList();
    });
    // controller
  }

  @override
  void dispose() {
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      // 提示用户
      if (page >= pages) return CustomToast.show('没有更多数据了');

      setState(() {
        page++;
      });
      getTaskList();
      // 提示用户
      CustomToast.success('数据加载完成');
    }
  }

  //  刷新数据
  Future<void> refreshTaskList() async {
    // 重置数据
    setState(() {
      page = 1;
      taskList = [];
    });
    getTaskList();
  }

  // 获取任务列表
  void getTaskList() async {
    if (Auth().checkAuth()) return;

    // 获取当前时间
    DateTime now = DateTime.now();

    // 格式化时间为 'yyyy-MM-dd' 格式
    String endTime =
        "${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}";

    try {
      var res = await http.get('/driver/tasks/list', params: {
        'endTime': endTime,
        'page': page,
        'pageSize': pageSize,
        'startTime': '2022-06-12',
        'status': 1,
      });
      setState(() {
        taskList.addAll(res['data']['items']);
        pages = int.parse(res['data']['pages']);
        totalCouont = int.parse(res['data']['counts']);
      });
    } catch (e) {
      CustomToast.error('无法获取任务列表');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.grey[200],
        padding: const EdgeInsets.only(left: 15, top: 15, right: 15),
        child: RefreshIndicator(
          onRefresh: () async {
            // 下拉刷新
            refreshTaskList();
          },
          child: totalCouont == 0
              ? EmptyComp(
                  desc: '无待提货物',
                )
              : CustomScrollView(
                  controller: _scrollController,
                  slivers: <Widget>[
                      SliverList.builder(
                          itemCount: taskList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              margin: EdgeInsets.only(bottom: 15),
                              child: TaskItem(
                                taskItem: taskList[index],
                              ),
                            );
                          })
                    ]),
        ));
  }
}
